<?php

namespace app\admin\command;

use app\admin\model\order\AppManage;
use app\common\library\TLSSigAPIv2;
use app\common\model\User;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\Db;

/*
 * 初始化IM账户信息
 * auth:wxfeng
 * data:2022.11.25
 */

class ImUserInit extends Command
{
    protected function configure()
    {
        $this->setName('ImUserInit')->setDescription("初始化IM账户信息");
    }

    protected function execute(Input $input, Output $output)
    {
        $output->writeln('ImUserInit start...');

        $appId = config('site.IM_AppID', '1400765204');
        $key = config('site.IM_key', '578f96825f4d6999f9a7ded16e727eebf75793e734135fd9874180d0eb31ad68');
        $identifier = config('site.IM_identifier', 'administrator');
        $UserSig = (new TLSSigAPIv2($appId, $key))->genUserSig($identifier);
        $random = random_int(1, 99999999);
        $im_url = "https://console.tim.qq.com/v4/im_open_login_svc/account_import?sdkappid=" . $appId . "&identifier=" . $identifier . "&usersig=" . $UserSig . "&random=" . $random . "&contenttype=json";
        $url = Db::name("config")->where(['name' => 'url'])->find();
        $app_id = (new AppManage())->getAppId($url['value']);
        $client = new \GuzzleHttp\Client();
        try {
            \addons\shopro\model\User::where("1=1")
                ->field("id,nickname,avatar")
                ->chunk(100, function ($users) use ($output, $app_id, $client, $im_url) {
                    foreach ($users as $user) {
                        $option = [
                            "UserID" => $app_id['id'] . '_' . $user['id'],
                            'Nick' => $user['nickname'],
                            'FaceUrl' => $user['avatar']
                        ];
                        $res = $client->request('POST', $im_url, [
                            'body' => json_encode($option)
                        ]);
                        $req = $res->getBody()->getContents();
                        $api_data = json_decode($req, true);
                        //错误码，0表示成功，非0表示失败
                        $output->writeln($option["UserID"] . "：" . $api_data['ActionStatus'] . " " . $api_data['ErrorInfo']);
                    }
                }, $field = 'id', $sort = 'asc');
        } catch (\Exception $e) {
            $output->writeln($e->getMessage() . ';第' . $e->getLine());
        }
        $output->writeln('ImUserInit end...');
    }
}
